package com.bjpowernode.front.controller;

import com.bjpowernode.common.constants.RedisKey;
import com.bjpowernode.common.enums.RCode;
import com.bjpowernode.common.util.CommonUtil;
import com.bjpowernode.front.service.SmsService;
import com.bjpowernode.front.view.RespResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Api(tags = "短信服务")
@RestController
@RequestMapping("/v1/sms")
public class SmsController extends BaseController{
    @Resource(name = "smsRegisterServiceImpl")
    private SmsService smsRegisterService;
    @Resource(name = "smsLoginServiceImpl")
    private SmsService smsLoginService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /*登录时发送短信验证码*/
    @ApiOperation(value = "登录时发送短信验证码",notes = "登录时发送短信验证码")
    @GetMapping("/code/login")
    public RespResult sendCodeLogin(@RequestParam String phone) {
        if (CommonUtil.checkPhone(phone)) {
            //判断redis中是否有验证码
            String code = stringRedisTemplate.opsForValue().get(RedisKey.KEY_SMS_LOGIN_PHONE + ":" + phone);
            if (code == null){
                boolean b = smsLoginService.sendSms(phone);
                if (b) {
                    return RespResult.ok(RCode.SEND_SMS_SUCCESS);
                }
                return RespResult.fail(RCode.SEND_SMS_FAIL);
            }else {
                return RespResult.fail(RCode.SMS_IS_EXIST);
            }
        }else {
            return RespResult.fail(RCode.PHONE_IS_ILLEGAL);
        }
    }

    /*注册时发送短信验证码*/
    @ApiOperation(value = "注册时发送短信验证码",notes = "注册时发送短信验证码")
    @GetMapping("/code/register")
    public RespResult sendCodeRegister(@RequestParam String phone) {
        if (CommonUtil.checkPhone(phone)) {
            //判断redis中是否有验证码
            String code = stringRedisTemplate.opsForValue().get(RedisKey.KEY_SMS_REGISTER_PHONE + ":" + phone);
            if (code == null){
                boolean b = smsRegisterService.sendSms(phone);
                if (b) {
                    return RespResult.ok(RCode.SEND_SMS_SUCCESS);
                }
                return RespResult.fail(RCode.SEND_SMS_FAIL);
            }else {
                return RespResult.fail(RCode.SMS_IS_EXIST);
            }
        }else {
            return RespResult.fail(RCode.PHONE_IS_ILLEGAL);
        }
    }
}
